
from transformers import VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer
import torch
from PIL import Image
import os
import sys
import json
print("获取到的图片路径参数："+str(sys.argv[1]))
argument = sys.argv[1].replace("/","\\").replace("'","")

print("替换后的图片路径参数："+argument)
images = argument.split(',')


print("开始加载模型")
model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
feature_extractor = ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)



max_length = 16
num_beams = 4
gen_kwargs = {"max_length": max_length, "num_beams": num_beams}
def predict_step(image_paths):
  images = []
  for image_path in image_paths:
    i_image = Image.open(image_path)
    if i_image.mode != "RGB":
      i_image = i_image.convert(mode="RGB")

    images.append(i_image)

  pixel_values = feature_extractor(images=images, return_tensors="pt").pixel_values
  pixel_values = pixel_values.to(device)

  output_ids = model.generate(pixel_values, **gen_kwargs)

  preds = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
  preds = [pred.strip() for pred in preds]
  return preds

#['E:\\codeserver\\imageCaptioning\\imageCaptioning\\tool\\1.jpg','E:\\codeserver\\imageCaptioning\\imageCaptioning\\tool\\1.jpg']
 # ['a woman in a hospital bed with a woman in a hospital bed']

print("开始预测")
predList = predict_step(images)
print("预测结果：")
print(predList)

file_name = os.path.basename(images[0])


'''
data结构
{
  "data":{
    文件名: {
      "文件名":
      "文件路径":
      "处理状态": 正在处理 处理完成 出错
      "处理结果": 描述性语言
    }
  }
}

'''

data = {}

if os.path.exists("E:\\nginx-1.8.0\\html\\temp\static\\result\\data.json"):
  with open("E:\\nginx-1.8.0\\html\\temp\static\\result\\data.json", "r") as infile:
      data = json.load(infile)

if data is None:
   data = {}

if "data" not in data:
  data["data"] = {}
count = 0
for i in predList:
    fileName = os.path.basename(images[count])
    fileData = {
      "fileName": fileName,
      "filePath": images[count],
      "state": "处理完成",
      "result": i
    }
    data["data"][fileName] = fileData


with open("E:\\nginx-1.8.0\\html\\temp\static\\result\\data.json", "w") as outfile:
    json.dump(data, outfile)

print("写入文件完成路径为："+"E:\\nginx-1.8.0\\html\\temp\static\\result\\data.json",)
# Reading from a file
# with open('path/to/file.txt', 'r') as f:
#     contents = f.read()
#     print(contents)